﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace Comarch.Animation
{
    public static class Extensions
    {
        public static void DelayCall(this Dispatcher dispatcher, Action action, int delayMs = 200)
        {
            ThreadPool.QueueUserWorkItem(delegate
                                             {
                                                 Thread.Sleep(delayMs);
                                                 dispatcher.BeginInvoke(action);
                                             });
        }

        public static void DelayCalls(this Dispatcher dispatcher, Func<IEnumerator<int>> action, int delay = 200)
        {
            dispatcher.DelayCall((Action)(() =>
                                              {
                                                  var enumerator = action();
                                                  if (!enumerator.MoveNext()) return;

                                                  DelayCalls(dispatcher, () => enumerator, enumerator.Current);
                                              }), delay);
        }

        public static List<UIElement> AddChildrenOf(this List<UIElement> allItems, Panel panel)
        {
            allItems.AddRange((IEnumerable<UIElement>)panel.Children);
            return allItems;
        }

        public static List<UIElement> AddChildrenOf(this List<UIElement> allItems, ItemsControl itemsControl)
        {
            return AddChildrenOf(allItems, itemsControl.GetItemsPanel());
        }

        public static List<UIElement> AddElements(this List<UIElement> allItems, params UIElement[] elements)
        {
            allItems.AddRange(elements);
            return allItems;
        }
    }
}